// 工具类
// 获取节点  简便方法
// 这是个jquser方法
/**
 * @name 获取节点
 * @description 根据返回器返回对应的节点
 * @param {string} sel
 * @returns 节点内容
 */
let local = require("./local.js");
let https = require("./https.js");
require("../assets/lib/weui/weui.css");
const weui = require("../assets/lib/weui/weui.js");

//获取单个DOM节点
function getEle(selector) {
  return document.querySelector(selector);
}

//获取多个DOM节点
function getEles(selector) {
  return document.querySelectorAll(selector);
}

function $(sel) {
  let flag = document.querySelectorAll(sel);
  if (!flag || flag.length == 0) {
    return console.error(`错误类型是${sel},没有获取到节点`);
  }

  // 当判断获取多个子元素为1的时候 说明 这是个获取单个节点的方法

  return flag.length == 1 ? flag[0] : flag;
}
//封装文档加载事件
/* 
    区别:
        load: 让所有资源加载完成后,才能执行js代码
        DOMContentLoaded: 只要DOM加载完成后,就可以执行js代码
*/
function ready(callback) {
  window.addEventListener("DOMContentLoaded", function () {
    isLogin();
    //当前页面的具体功能
    callback(); //把 使用时function中的功能全部执行到这个位置
  });
}
// 点击跳页面功能;
function jump(dom, target) {
  getEle(dom).addEventListener("click", function () {
    location.href = `${target}.html`;
  });
}
/**
 * @name 生成页脚
 * @description 先写个footer
 * @param {string} create
 * @returns 节点内容
 */
function createFoot(num) {
  let foot = $("footer");
  foot.classList.add("fix");
  foot.innerHTML = `
  <ul class="disflex just-sp-eve alin-cent">
          <li class="home">
            <span class="iconfont icon-home" alt=""></span>
            <p>首页</p>
          </li>
          <li>
            <span class="iconfont icon-sport" alt=""></span>
            <p>运动</p>
          </li>
          <li>
            <span class="iconfont icon-circle" alt=""></span>
            <p>圈子</p>
          </li>
          <li>
            <span class="iconfont icon-mine" alt=""></span>
            <p>我的</p>
          </li>
        </ul>
  `;
  let arr = ["home", "sportsClass", "circle", "myhome"];
  $("ul li").forEach((element, i) => {
    $("ul li")[num].classList.add("active");
    element.addEventListener("click", function () {
      $("ul li").forEach((v) => {
        v.classList.remove("active");
      });
      console.log(arr[i]);
      location.href = `${arr[i]}.html`;
      element.classList.add("active");
    });
  });
}
//  封裝add事件
function addEvent(node, callback, type = "click") {
  $(node).addEventListener(type, function () {
    callback();
  });
}

//封装事件注册功能
function addEvent(dom, callback, type = "click") {
  getEle(dom).addEventListener(type, callback);
}
//是否登录
const isLogin = () => {
  if (!local.get("t_k")) location.href = "login.html";
};
//导出
module.exports = {
  $,
  ready,
  getEle,
  getEles,
  jump,
  createFoot,
  isLogin,
  addEvent,
};
